package com.xx;


import com.pojo.User;
import lombok.RequiredArgsConstructor;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author frank
 * @description 导出Excel文件控制器
 * @date 2021/12/18 14:06
 */
@RestController
@RequiredArgsConstructor
public class MyExcelExportController {

    private final List<User> userList=new ArrayList<User>();

    {
        userList.add(new User("张三", "北京", "123456", "13812345678"));
        userList.add(new User("李四", "上海", "123456", "13812345678"));
        userList.add(new User("王五", "深圳", "123456", "13812345678"));
    };
    @GetMapping(value = "/hello")
    public String hello() {
        return "hello";
    }

    @GetMapping(value = "/excel")
    public void exportExcel(HttpServletResponse response) throws UnsupportedEncodingException {
        List<User> list = userList;
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();

        XSSFRow row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("姓名");
        row0.createCell(1).setCellValue("地址");
        row0.createCell(2).setCellValue("密码");
        row0.createCell(3).setCellValue("电话");
        for (int i = 0; i < list.size(); i++) {
            XSSFRow row = sheet.createRow(i + 1);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue(list.get(i).getName());
            XSSFCell cell1 = row.createCell(1);
            cell1.setCellValue(list.get(i).getAddress());
            XSSFCell cell2 = row.createCell(2);
            cell2.setCellValue(list.get(i).getPassword());
            XSSFCell cell3 = row.createCell(3);
            cell3.setCellValue(list.get(i).getPhone());
        }

        response.setCharacterEncoding("UTF-8");
        //让服务器告诉浏览器它发送的数据属于什么文件类型
        response.setHeader("content-Type", "application/vnd.ms-excel");
        //当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("b.xlsx", "UTF-8"));

        try {
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
